package com.klun.spring4.b_four.four3;

import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.WritableResource;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileSourceExample {
    public static void main(String[] args) {
        try{
            String filePath = "E:/klun/springFour/src/main/resources/test/file1.txt";

            //1 使用系统文件路径方式加载文件
            WritableResource resource1 = new PathResource(filePath);

            //2 使用类路径方式加载文件
            Resource resource2 = new ClassPathResource("test/file1.txt");

            //3 使用 WritableResource 接口写资源文件
            OutputStream stream1 = resource1.getOutputStream();
            stream1.write("欢迎光临\n小王论坛".getBytes());
            stream1.close();

            //4 使用 Resource 接口读取资源文件
            InputStream inputStream1 = resource1.getInputStream();
            InputStream inputStream2 = resource2.getInputStream();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int i;
            while ((i = inputStream1.read())!=-1){
                baos.write(i);
            }

            System.out.println(baos.toString());

            System.out.println("resource1:"+resource1.getFilename());
            System.out.println("resource2:"+resource2.getFilename());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
